﻿namespace Example.Cryptography
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Security.Cryptography;

    [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rsa", Justification = "The casing is correct.")]
    public sealed class RsaSettings
    {
        private string _key;

        public RsaSettings(string key)
        {
            Key = key;
        }

        private string Key
        {
            get
            {
                return _key;
            }

            set
            {
                if (null == value)
                {
                    throw new ArgumentNullException("value");
                }

                _key = value;
            }
        }

        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "ciphertext", Justification = "The casing is correct.")]
        public RsaPlaintext Decrypt(RsaCiphertext ciphertext)
        {
            if (null == ciphertext)
            {
                throw new ArgumentNullException("ciphertext");
            }

            RsaPlaintext plaintext;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(Key);
                plaintext = new RsaPlaintext(rsa.Decrypt(ciphertext.ToBytes(), false));
            }

            return plaintext;
        }

        public RsaCiphertext Encrypt(RsaPlaintext plaintext)
        {
            if (null == plaintext)
            {
                throw new ArgumentNullException("plaintext");
            }

            RsaCiphertext ciphertext;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(Key);
                ciphertext = new RsaCiphertext(rsa.Encrypt(plaintext.ToBytes(), false));
            }

            return ciphertext;
        }
    }
}